package org.springblade.gateway.handler;

import cn.hutool.json.JSONObject;
import com.wf.captcha.ArithmeticCaptcha;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springblade.common.cache.CacheNames;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.server.HandlerFunction;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.reactive.function.server.ServerResponse;
import reactor.core.publisher.Mono;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * 验证码生成类
 */
@Slf4j
@Component
@AllArgsConstructor
public class ImageCodeHandler implements HandlerFunction<ServerResponse> {
	private final RedisTemplate redisTemplate;
	@Override
	public Mono<ServerResponse> handle(ServerRequest serverRequest) {
		ArithmeticCaptcha arithmeticCaptcha = new ArithmeticCaptcha(130, 48, 2);
		String verCode = arithmeticCaptcha.text();
		String key = UUID.randomUUID().toString();
		// 存入redis并设置过期时间为30分钟
		redisTemplate.opsForValue().set(CacheNames.CAPTCHA_KEY + key, verCode, 30L, TimeUnit.MINUTES);
		// 将key和base64返回给前端
		JSONObject jsonObject = new JSONObject();
		jsonObject
			.put("key",key)
			.put("image",arithmeticCaptcha.toBase64())
			.put("code",200)
			.put("msg","操作成功");
		return ServerResponse
			.status(HttpStatus.OK)
			.contentType(MediaType.APPLICATION_JSON)
			.body(BodyInserters.fromValue(jsonObject));
	}
}
